<template>
  <div class="chart" id="dateChart"></div>
</template>
<script>
import * as echarts from "echarts";
var dateChart;
export default {
  name: "FlightDateChart",
  props: ["flights"],
  data() {
    return {
      maxTotal: 0,
      option: {
        visualMap: [
          {
            show: false,
            type: "continuous",
            seriesIndex: 0,
            min: 0,
            max: 400
          }
        ],
        title: {
          text: "日期分布",
          left: "center"
        },
        tooltip: {
          trigger: "axis"
        },
        legend: {
          type: "scroll",
          orient: "vertical",
          left: "right",
          data: ["航班数"]
        },
        xAxis: {
          type: "category",
          data: []
        },
        yAxis: {
          type: "value"
        },
        series: [
          {
            name: "航班数",
            type: "line",
            data: [],
            lineStyle: {
              width: 5, // 设置线宽
              type: "solid" //'dotted'虚线 'solid'实线
            },
            itemStyle: {
              // 拐点上显示数值
              label: {
                show: true
              }
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)"
              }
            }
          }
        ]
      }
    };
  },
  methods: {
    // 计算图例
    formatDateDH(dateString) {
      // 获取日期
      var date = new Date(dateString);
      var MM = date.getMonth() + 1;
      if (MM < 10) MM = "0" + MM;
      var DD = date.getDate();
      if (DD < 10) DD = "0" + DD;
      return MM + "-" + DD;
    },
    calDates(flights) {
      var data = [];
      for (let flight of flights) {
        var date = this.formatDateDH(flight.startTime);
        if (data.indexOf(date) == -1) {
          data.push(date);
        }
      }
      return data;
    },
    // 计算数据
    calTotal(dates, flights) {
      var data = [];
      for (let date of dates) {
        data.push({
          value: 0,
          name: date
        });
      }
      for (let flight of flights) {
        var pos = dates.indexOf(this.formatDateDH(flight.startTime));
        data[pos].value++;
        this.maxTotal =
          data[pos].value > this.maxTotal ? data[pos].value : this.maxTotal;
      }
      return data;
    }
  },
  computed: {},
  watch: {
    flights: function(newval, oldval) {
      dateChart.showLoading();
      var dates = this.calDates(newval).sort();
      var data = this.calTotal(dates, newval);
      this.option.series[0].data = data;
      this.option.xAxis.data = dates;
      this.option.visualMap[0].max = this.maxTotal;
      dateChart.hideLoading();
      dateChart.setOption(this.option);
    }
  },
  mounted() {
    dateChart = echarts.init(document.getElementById("dateChart"));
  }
};
</script>

<style scoped>
.chart {
  width: 600px;
  height: 300px;
}
</style>